#!/usr/bin/env python
# Simple script to package actual observed conditions into a pickled dictionary
import sys
sys.path.append('..')
# Use the option parser to manually specify today's verification values
from optparse import OptionParser
parser = OptionParser()

parser.add_option('-i', '--high',dest='high', action = 'store', type='int', default=None, help = "Today's high temp")
parser.add_option('-l', '--low', dest='low', action = 'store', type='int', default=None, help = "Today's low temp")
parser.add_option('-w', '--winds', dest='winds', action = 'store', type='int', default=None, help = "Today's max wind (mph)")
parser.add_option('-p', '--precip', dest='precip', action = 'store', type='string', default=None, help = "Today's precip (to hundredth of inch '0.00')")
parser.add_option('-d', '--date', dest='date', action = 'store', type='int', default=None, help = "Day of month")
parser.add_option('-m', '--model', dest='model', action = 'store', type='string', default=None, help = "Dummy variable for funct. call")
parser.add_option('-v', '--variable', dest='variable', action = 'store', type='string', default=None, help = "Dummy variable for funct. call")
parser.add_option('-s', '--site', dest='site', action = 'store', type='string', default=None, help = "Dummy variable for funct. call")
parser.add_option('-e', '--export', dest='export_flag', action = 'store_true', default=False, help = "Dummy variable for funct. call")


(opts,args) = parser.parse_args()

date = opts.date
high = opts.high
low =  opts.low
winds = opts.winds
precip = opts.precip

from INFILE import siteid, wfoid, maindir

site = siteid.upper()
WFO = wfoid.upper()




def encode_truth(siteid):
    from datetime import datetime
    import re, os
    # Read in climo reports
    allfiles = os.listdir('%s/site_data' % maindir)
    filelist = [f for f in allfiles if f.startswith(siteid.upper()) and f.endswith('.cli')]
    filelist.sort()
    #filelist = ['KMSY_201112.cli','KMSY_201201.cli']
    #print filelist
    #raw_input()

    actual_values = {}
    #    'dates' : [],
    #'highs' : [],
    #    'lows'  : [],
    #    'winds' : [],
    #    'precip': [],
    #    }

    for file in filelist:
        year,month = re.search('(\d{4})(\d{2})',file).groups()
        infile = open('%s/site_data/%s' % (maindir,file),'r')
        for line in infile:
            matcher = re.compile('( \d{1}|\d{2}) (-?\d{2}| -?\d{1})') # -?\d{1,2} -?\d{1,2} -?\d{1,2}')
            if matcher.match(line):
                # We've found an ob line!
                lsp = line.split()
                day = int(lsp[0])
                curdt = datetime(int(year), int(month), day)
                actual_values[curdt] = {}
                actual_values[curdt]['high'] = float(lsp[1])
                actual_values[curdt]['low'] = float(lsp[2])
                if lsp[11] == 'M':
                    actual_values[curdt]['wind'] = 0.0
                else: 
                    actual_values[curdt]['wind'] = float(lsp[11])*0.868976
                # Tricky for precip
                if lsp[7] == 'T':                
                    actual_values[curdt]['precip'] = 0.00
                else:
                    actual_values[curdt]['precip'] = float(lsp[7])
    #print actual_values['dates']
    #print actual_values['highs']
    #print actual_values['lows']
    #print actual_values['winds']
    return actual_values




def update_truth(site,WFO,date=None,high=None,low=None,winds=None,precip=None):
    # Get the latest file from the NWS website
    import re
    from datetime import datetime, timedelta
    from urllib import urlopen
    import subprocess
    #base_address = 'http://www.nws.noaa.gov/view/validProds.php?prod=CF6&node=%s' % WFO
    #webin = urlopen(base_address)
    #inbufr = webin.read()
    #webin.close()
    # Switch to local command
    cf6out = subprocess.Popen('/usr/local/wx/bin/cf6 %s' % site.lower(), shell=True,\
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    inbufr = cf6out.stdout.read()

    file_found = False
    blocks = inbufr.split('000')
    for block in blocks:
        if re.search('CF6%s' % site[1:].upper(),block) and not file_found:
            # Just for HILO
            #if re.search('CF6%s' % 'ITO',block) and not file_found:
            print "Site found!"
            file_found=True
            # Find the month and year to make sure we're right
            curyear = re.search('YEAR:      (\d{4})',block).groups()[0]
            curmonth = re.search('MONTH:     (\D{3,9})',block).groups()[0]
            curyear = curyear
            curmonth = curmonth.strip()  # Gets rid of newlines and whitespace
            datestr = curmonth + ' ' + curyear 
            filedate = datetime.strptime(datestr,'%B %Y')
            #print filedate
            # We need to be sure it only updates the current month
            now = datetime.now()
            nowstr = now.strftime('%Y%m')
            #raw_input()
            if nowstr == filedate.strftime('%Y%m'):
                outfile = open('%s/site_data/%s_%s.cli' % (maindir,site.upper(),filedate.strftime('%Y%m')),'w')
                for line in block.split('\n'):
                    if not line.startswith('SM'):
                        print >>outfile, line
                    elif date != None:
                        # We've submitted data to append for today's date (Hopefully)
                        now = datetime.now()
                        if now.day != date:
                            print "Input data is not for today.  Please edit the record manually."
                        else:
                            print "Adding today's data as option."
                            winds = int(winds*1.15077945)
                            print >> outfile, "%2d %3d %3d  99   9  99  99 %s  0.0    0  0.0 %2d" % (date,high,low,precip,winds)
                    else:
                        print >>outfile, line
                outfile.close()
            else:
                # This must be the previous month.  Clear the data.
                #try:
                newdate = filedate.replace(day=1)
                newdate = newdate + timedelta(days=32)
                infile = open('%s/site_data/%s_%s.cli' % (maindir,site.upper(),filedate.strftime('%Y%m')),'r')
                block = infile.read()
                infile.close()
                #except:
                #    print "Unable to find file for new month."
                #    exit(1)                    

                outfile = open('%s/site_data/%s_%s.cli.new' % (maindir,site.upper(),newdate.strftime('%Y%m')),'w')
                for line in block.split('\n'):
                    try:
                        startnum = int(line.split()[0])
                    except:
                        startnum = 87654321
                    if startnum in range(2,32):
                        pass
                    elif startnum == 1 and date != None:
                        # We've submitted data to append for today's date (Hopefully)
                        now = datetime.now()
                        if now.day != date:
                            print "Input data is not for today.  Please edit the record manually."
                        else:
                            print "Adding today's data as option."
                            winds = int(winds*1.15077945)
                            print >> outfile, "%2d %3d %3d  99   9  99  99 %s  0.0    0  0.0 %2d" % (date,high,low,precip,winds)
                    else:
                        print >>outfile, line
                outfile.close()
                import os
                os.system('mv %s/site_data/%s_%s.cli.new %s/site_data/%s_%s.cli' %(maindir,site.upper(),newdate.strftime('%Y%m'),maindir,siteid.upper(),newdate.strftime('%Y%m')))

if date != None:
    update_truth(site,WFO,date,high,low,winds,precip)
